import json
from datetime import datetime
import random

import requests

from app import ExceptionApi, Code, env
from app.Models.FNDs import FNDs
from app.Models.Model import SapMaterialDetailsInfo, DoorVehicle


def get_material_details_from_sap(vehicle_part):
    """
    根据整车物料号在SAP中获取详细物料信息
    """
    print('根据整车物料号在SAP中获取详细物料信息:',vehicle_part)
    url = env.SAP_HOST + env.SAP_MATERIAL
    headers = {
        "Authorization": "Basic Q1lDU1BTOmNoZXJ5Q1lDU1BTQDIwMjI=",
        "Content-Type": "application/json",
        "reqId": str(random.randint(10000000,99999999)),
        "reqFrom": "LZAI",
        "reqTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    }
    data = {
        "I_MATNR": vehicle_part,
        "I_WERKS": '1000'
    }
    try:
        response = requests.get(url, headers=headers, json=data)
        if response.status_code == 200:
            material_list = []
            if response.json()['rtnCode'] == 'F':
                return []
            fnds = FNDs()
            gpc_fnd = fnds.get_all_gpc_fnd()
            strat_time = datetime.now()
            for material in response.json()['rtnData']:
                if material['TEXT1'] in gpc_fnd:
                    material_info = SapMaterialDetailsInfo()
                    material_info.werks = material['WERKS']
                    material_info.matnr = material['MATNR']
                    material_info.maktx1 = material['MAKTX1']
                    material_info.idnrk = material['IDNRK']
                    material_info.maktx2 = material['MAKTX2']
                    material_info.menge = material['MENGE']
                    material_info.text1 = material['TEXT1']
                    material_info.text2 = material['TEXT2']
                    material_info.text3 = material['TEXT3']
                    material_info.text4 = material['TEXT4']
                    material_info.text5 = material['TEXT5']
                    material_info.text6 = material['TEXT6']
                    material_list.append(material_info)
            end_time = datetime.now()
            time_diff = end_time - strat_time
            print('筛选门户板零件耗时：',int(time_diff.total_seconds() * 1000 + time_diff.microseconds / 1000))
            return material_list
        
        else:
            raise ExceptionApi(Code.ERROR,
                               f"根据整车物料号在SAP中获取详细物料信息请求失败，状态码：{response.status_code}")
    except Exception as e:
        raise ExceptionApi(Code.ERROR, f"根据整车物料号在SAP中获取详细物料信息请求失败，异常信息：" + str(e))


def get_10_vehicle_list():
    """
    根据整车物料号在SAP中获取详细物料信息
    """
    headers = {
        "Authorization": "Basic Q1lDU1BTOmNoZXJ5Q1lDU1BTQDIwMjI=",
        "Content-Type": "application/json",
        "reqId": "55698669",
        "reqFrom": "SPS",
        "reqTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    }
    data = {
        "wcName": 'Z055'
    }
    try:
        response = requests.post(env.LOT_10_VEHICLE_LIST_URL, headers=headers, data=json.dumps(data))
        if response.status_code == 200:
            vehicle_list = []
            if response.json()['responseStatus'] == 'OK':
                rs_data = response.json()['data']
                if rs_data:

                    for vehicle_info in rs_data['list']:
                        vehicle = DoorVehicle()
                        vehicle.vin = vehicle_info['vin']
                        vehicle.vehicle_part = vehicle_info['vehiclePart']
                        vehicle_list.append(vehicle)
                    return vehicle_list
            return []
        else:
            raise ExceptionApi(Code.ERROR,
                               f"根据整车物料号在SAP中获取详细物料信息请求失败，状态码：{response.status_code}")
    except Exception as e:
        raise ExceptionApi(Code.ERROR, f"根据整车物料号在SAP中获取详细物料信息请求失败，异常信息：" + str(e))


if __name__ == '__main__':
    get_material_details_from_sap(vehicle_part="M7150PNBWLD0004", work_no="1000")
